<template>
    <div class="" v-if="!empty">
        <ul class="storeList">
            <li v-for="shop in shopCar" :key="shop.shopId">
                <div class="storeInfo">
                    <van-checkbox v-model="shop.checked"  @click="shopCheckedChange(shop.shopId)" @change="isAllChecked" :name="shop.shopId"></van-checkbox>
                    <i class="van-icon van-icon-shop-o"></i>
                    <em>{{shop.shopName}}</em>
                </div>
                <ul class="goodsList">
                    <van-swipe-cell :right-width="100"  v-for="goods in shop.goodsList" :key="goods.cartId">
                        <li class="item">
                            <div class="select">
                                <van-checkbox v-model="goods.checked" @click="goodsCheckedChange(goods.cartId, shop.shopId)" @change="shopCount"></van-checkbox>
                            </div>
                            <img :src="'/images/' + goods.shopGoods.titleImage"  class="img">
                            <div class="content">
                                <div class="name">{{goods.shopGoods.simpleTitle}}</div>
                                <div class="sku">{{goods.shopGoodsSpec.name}}</div>
                                <div class="other">
                                    <div class="price">¥<em>{{goods.shopGoodsSpec.memberPrice | money}}</em></div>
                                    <van-stepper v-model="goods.productNum" :min="1" :max="goods.shopGoodsSpec.stockQuantity" @change="shopCount"/>
                                </div>
                            </div>
                        </li>
                        <span slot="right" class="delBtn" @click="delGoods(goods.cartId, goods.shopId)">删除</span>
                    </van-swipe-cell>
                </ul>

                <div class="tips  vux-1px-t">
                    重量:&nbsp;<span>¥<em>{{shop._weight | weight }}Kg</em></span>
                    运费:&nbsp;<span>¥<em>{{shop._freight | money}}</em></span>
                    商品总计:&nbsp;<span>¥<em>{{shop._money | money}}</em></span>
                </div>
            </li>
        </ul>

        <van-submit-bar
            :button-text="`去结算(${goodsCount})`"
            :loading="loading"
            @submit="onSubmit"
            >
            <div class="defaultSlot">
                <van-checkbox v-model="allChecked" style="padding-left: 12px;" @click="allCheckedChange">全选</van-checkbox>
                <div class="moneyInfo">
                    <div class="money">合计:&nbsp;<span>¥<em>{{allMoney | money}}</em></span></div>
                    <div class="freight">运费:<span>¥<em>{{allFreight | money}}</em></span></div>
                </div>
            </div>
        </van-submit-bar>
    </div>
    <div v-else>
        <div class="empty-list"><h2>购物车快饿瘪了T.T</h2><div class="desc">快给我挑点宝贝</div><div class="go-homepage-btn"><a @click="$router.push('/index')">去逛逛</a></div></div>
    </div>
</template>

<script>
let setTimeoutInstance = null;
export default {
    name: 'shopCar',
    data() {
        return {
            allChecked: false, //全选按钮
            loading: false, //去结算 的时候的加载开关
            goodsCount: 0, //选中的商品数量

            allFreight: 0, //总运费
            allMoney: 0, //总金额
            shopCar: {},

            empty: false,
        }
    },

    methods: {
        getShopCar() {
            this.$http.post('/shop/shoppingCart/front/getShoppingCartList',{}).then(res => {
                if (res.status === 0) {
                    let data = res.data;
                    if (res.data.shoppingCartGoodsVoList.length === 0) {
                        this.empty = true;
                        return;
                    }
                    let shopCar = {};
                    
                    //先分类店铺
                    data.shopShopsVo.forEach(e => {
                        shopCar[e.shopId] ? shopCar[e.shopId] : (shopCar[e.shopId] = Object.assign({goodsList: [], checked: false, _money: 0, _weight: 0, _feright: 0}, e));
                    });

                    //再把商品归类到店铺
                    data.shoppingCartGoodsVoList.forEach(e => {
                        let _stack = shopCar[e.shopId].goodsList;
                        e.checked = false;
                        _stack.push(e);
                    })

                    this.shopCar = shopCar;
                    
                } else {
                    this.$toast.fail(res.message);
                }
            })
        },

        shopCheckedChange(value) {
            let checked = this.shopCar[value].checked;
            this.shopCar[value].goodsList.forEach(e => {
                e.checked = checked;
            });
            
        },
        goodsCheckedChange(cartId, shopId) {
            let goodsList = this.shopCar[shopId].goodsList;
            let goodsChecked = goodsList.filter(e => e.checked);
            this.shopCar[shopId].checked = (goodsChecked.length === goodsList.length);
        },
        //点击全选按钮
        allCheckedChange() {
            for (let i in this.shopCar) {
                let e = this.shopCar[i];
                e.checked = this.allChecked;
                this.shopCheckedChange(e.shopId);
            }
        },
        //判断是否全选  
        isAllChecked() {
            let keys = Object.keys(this.shopCar);
            this.allChecked = (keys.filter(e => this.shopCar[e].checked).length === keys.length);
            
        },


        //统计总金额
        shopCount() {
            if (setTimeoutInstance) {
                //防抖
                clearTimeout(setTimeoutInstance);
            }
            setTimeoutInstance = setTimeout(() => {
                let allMoney = 0; //总价
                let allFreight = 0; //运费
                let goodsCount = 0; //数量
                for (let i in this.shopCar) {
                    let money = 0, //店铺下所选的金额
                        weight = 0, //店铺下的重量
                        freight = 0; //店铺下的运费
                    let shop = this.shopCar[i];
                    shop.goodsList.forEach(goods => {
                        if (goods.checked) {
                            goodsCount++;
                            money += goods.shopGoodsSpec.memberPrice * goods.productNum;
                            weight += goods.shopGoodsSpec.weight * goods.productNum;
                        }
                    })
                    freight = this.calcFreightAmount(shop.postFreeAmount, shop.logisticsArea.split(","), money, weight);
                    allMoney += money;
                    allFreight += freight;
                    shop._weight = weight;
                    shop._money = money;
                    shop._freight = freight;
                }

                this.allMoney = allMoney;
                this.allFreight = allFreight;
                this.goodsCount = goodsCount;
            }, 300)
        }, 
        //计算运费
        calcFreightAmount(shopPostFreeAmount,shopLogisticsArea,shopTotalAmount,shopTotalWeight){
            var freightAmount=0;
            if(shopTotalWeight==0){
                return freightAmount;
            }
            //首重,首费,续重,续费
            var sz=parseInt(shopLogisticsArea[0]),sf=parseInt(shopLogisticsArea[1]),xz=parseInt(shopLogisticsArea[2]),xf=parseInt(shopLogisticsArea[3]);
            if(shopTotalAmount>=shopPostFreeAmount){
                return freightAmount;
            }
            if(shopTotalWeight<=sz){
                freightAmount=sf;
                return freightAmount;
            }
            shopTotalWeight=shopTotalWeight-sz;
            freightAmount=sf+xf*Math.ceil(shopTotalWeight/xz);
            return freightAmount;
        },

        delGoods(id, shopId) {
            this.$http.post('/shop/shoppingCart/front/delShoppingCart', {
                cartId: id
            }).then(res => {
                if (res.status === 0) {
                    this.$toast.success('删除成功');
                    this.shopCar[shopId].goodsList = this.shopCar[shopId].goodsList.filter(e => e.cartId !== id);
                    if (this.shopCar[shopId].goodsList.length === 0) {
                        delete this.shopCar[shopId];
                    }
                    if (Object.keys(this.shopCar).length === 0) {
                        this.empty = true;
                    }
                    this.shopCount();
                } else {
                    this.$toast.fail(res.message);
                }
            })
        },

         
        onSubmit() {
            // if (!this.checked) {
            //     this.$toast('请选择商品');
            //     return;
            // }
            // this.loading = true;
            // setTimeout(() => {
            //     this.$toast.success('提交成功');
            //     this.loading = false;
            // }, 1400)
            let cartParams = [], cartIds = [];
            for (let i in this.shopCar) {
                let shop = this.shopCar[i];
                shop.goodsList.forEach(goods => {
                    if (goods.checked) {
                        cartParams.push(`${goods.shopId}-${goods.goodsId}-${goods.goodsSpecId}-${goods.productNum}`);
                        cartIds.push(goods.cartId)
                    }
                })
            }

            if (cartIds.length === 0) {
                this.$toast('请选择商品');
                return;
            }
            this.loading = true;
            this.$http.post('/shop/order/front/addOrder', {
                cartParams: cartParams.toString(),
                cartIds: cartIds.toString()
            }).then(res => {
                this.loading = false;
                if (res.status === 0) {
                    this.$toast.success('提交成功');
                    setTimeout(() => {
                        this.$router.push({path: '/order/payOrder', query: {order: res.data}});
                    }, 700)
                } else {
                    this.$toast.fail(res.message);
                }
            })
        }
    },

    created() {
        this.getShopCar();
    }
}
</script>

<style scoped lang="scss">
.storeList {
     > li {background-color: #fff; margin-bottom: 10px; box-shadow: 0 0 5px 0 rgba(0,0,0,.1)}
    .storeInfo {
        display: flex;
        align-items: center;
        padding: 10px 12px;
        i {
            font-size: 16px;
            margin: 0 5px 0 8px;
        }

        em {
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            flex: 1;
            box-sizing: border-box;
            display: inline-block;
            font-size: 16px;
            font-weight: 700;
            margin-right: 10px;
            width: 100%;
        }
    }   

    .tips {
        font-size: 12px;
        line-height: 30px;
        text-align: right;
        padding: 0 5px;
        border-color: #ccc;
        span {
            color: #f44;
            margin-right: 5px;
        }
    }
    
    .goodsList {
        .item {
            position: relative;
            overflow: hidden;
            background: #fff;
            z-index: 1;
            position: relative;
            min-height: 75px;
            padding: 5px 10px 15px 128px;
            background: #fff;
            -webkit-overflow-scrolling: touch;

            .select {
                z-index: 1;
                display: block;
                position: absolute;
                top: 0;
                left: 0;
                width: 63px;
                height: 100%;
                padding-top: 30px;
                padding-left: 12px
            }

            .img {
                position: absolute;
                left: 43px;
                top: 5px;
                display: block;
                width: 75px;
                height: 75px;
            }

            .content {
                min-height: 75px;
                .name {
                    font-size: 14px;
                    margin-bottom: 5px;
                    word-break: break-all;
                        overflow: hidden;
                    text-overflow: ellipsis;
                    display: -webkit-box;
                    -webkit-line-clamp: 2;
                    -webkit-box-orient: vertical;
                }
                .sku {
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                    position: relative;
                    background-color: #fff;
                    padding: 0;
                    border: none;
                    margin: 0;
                    font-size: 12px;
                    color: #999;
                    border-radius: 2px;
                }

                .other {
                    position: relative;
                    display: -webkit-box;
                    display: -webkit-flex;
                    display: flex;
                    -webkit-box-align: center;
                    -webkit-align-items: center;
                    align-items: center;
                    margin: 5px 0 0;
                    -webkit-box-pack: justify;
                    -webkit-justify-content: space-between;
                    justify-content: space-between;
                    .price {
                        flex: 1;
                        line-height: 16px;
                        color: #e93b3d;
                        font-size: 10px;
                        em {
                            font-size: 16px;
                        }
                    }
                }
            }
        }
    }
}

.defaultSlot {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .moneyInfo {
        text-align: right;
        .money {
            font-weight: 500;
            text-align: right;
            color: #323233;
            font-size: 14px;
            span {
                color: #f44;
                margin-left: 5px;
                em {
                    font-size: 18px;
                    padding: 0 5px;
                }
            }
        }

        .freight {
            font-size: 14px; 
            color: #999;
            span {
                margin-left: 5px;
                em {
                    padding: 0 5px;
                }
            }
        }
    }
}

/deep/ .van-submit-bar__text { display: none;}

.delBtn {
    color: #fff;
    font-size: 15px;
    width: 100px;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f44;
}
.empty-list {
    padding: 60px 0;
    text-align: center;
    h2 {
        font-size: 16px;
        color: #666;
        margin-bottom: 10px;
        font-weight: 400;
    }

    .desc {
        font-size: 14px;
        color: #999;
    }

    .go-homepage-btn {
        box-sizing: border-box;
        width: 104px;
        height: 36px;
        line-height: 18px;
        padding: 8px 0;
        font-size: 14px;
        border: 1px solid #f60;
        margin: 30px auto 0;
        color: #f60;
        border-radius: 3px;
    }
}
</style>
